
package com.rssfeed.parser;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.select.Elements;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.util.Log;

import com.rssfeed.model.RSSFeed;
import com.rssfeed.utility.Utility;

public class NewsFeedParser {
    private InputStream urlStream;
    private XmlPullParserFactory factory;
    private XmlPullParser parser;

    private List<RSSFeed> rssFeedList;
    private RSSFeed rssFeed;

    private String urlString;
    private String tagName;

    private String title;
    private String link;
    private String description;
    private String pubDate;
    private String imgLink;
    private String feedId;
    private String mp3Link;

    

    public static final String ITEM = "item";
    public static final String CHANNEL = "channel";
    public static final String TITLE = "title";
    public static final String LINK = "link";
    public static final String DESCRIPTION = "description";
    public static final String PUBLISHEDDATE = "pubDate";
    public static final String IMAGELINK = "enclosure";

    
    public NewsFeedParser(String urlString) {
        this.urlString = urlString;
    }

    public static InputStream downloadUrl(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.connect();
        InputStream stream = conn.getInputStream();
        return stream;
    }
    
    public List<RSSFeed> parse() {
        try {
            factory = XmlPullParserFactory.newInstance();
            parser = factory.newPullParser();
            urlStream = downloadUrl(urlString);
            parser.setInput(urlStream, null);
            int eventType = parser.getEventType();
            boolean done = false;
            rssFeed = new RSSFeed();
            rssFeedList = new ArrayList<RSSFeed>();
            while (eventType != XmlPullParser.END_DOCUMENT && !done) {
                tagName = parser.getName();

                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
                        if (tagName.equals(ITEM)) {
                            rssFeed = new RSSFeed();
                        }
                        if (tagName.equals(TITLE)) {
                            title = parser.nextText().toString();
                        }
                        if(tagName.equalsIgnoreCase(DESCRIPTION)){
                        	StringBuffer newStringBuffer = new StringBuffer(parser.nextText().toString()
                        														.replaceAll("&#160;", "")
                        														.replaceAll("&#39;", "'")
                        														.replaceAll("&quot;", "\"")
                        														.replaceAll("(\r?\n){3,}", "\r\n\r\n"));
                        	description = newStringBuffer.toString();
                        }
                        if (tagName.equals(LINK)) {
                        	// get link of feed
                            link = parser.nextText().toString();
                            //get id from link of feed
                            String[] str = link.split("/");
                            String id = str[str.length-1];
                            feedId = id.substring(0, id.length() - 5);
                            //parse mp3 link 
                            /*Elements elmUrl = new ParseHtmlAsyncTask().execute(link,Utility.newtag).get();
                            mp3Link = elmUrl.attr("href");
                            Log.d("mp3", "=" + mp3Link);*/
                        }
                        if (tagName.equals(PUBLISHEDDATE)) {
                            pubDate = parser.nextText().toString();
                        }
                        if(tagName.equals(IMAGELINK)){
                        	imgLink = parser.getAttributeValue(null, "url");
                        }

                        break;
                    case XmlPullParser.END_TAG:
                        if (tagName.equals(CHANNEL)) {
                            done = true;
                        } else if (tagName.equals(ITEM)) {
                            rssFeed = new RSSFeed(feedId, title, link,description, pubDate,imgLink,null);
                            rssFeedList.add(rssFeed);
                        }
                        break;
                }
                eventType = parser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return rssFeedList;

    }
}
